Ext.ns('Lone.Click.Canvas');

Lone.Click.Canvas.MinesWeeper = function(config) {
	Ext.apply(this, config);
	this.initComponent();
};

Ext.extend(Lone.Click.Canvas.MinesWeeper, Ext.emptyFn, {
	height : null,
	width : null,
	dom : null,
	context : null,
	row : null,
	col : null,
	bombs : [],
	bombsNum : null,
	initComponent : function() {
		this.dom = Ext.DomQuery.jsSelect('#canvas')[0];
		this.context = this.dom.getContext('2d');
		this.height = this.dom.height;
		this.width = this.dom.width;

		this.boxImage = new Image();
		Ext.apply(this.boxImage, this.boxImageConfig);

		Ext.EventManager.addListener(this.dom, 'click', this.onCanvasClick,
				this);
		Ext.EventManager.addListener(this.boxImage, 'load',
				this.onBoxImageLoaded, this);
		this.initCanvas();
	},

	initCanvas : function() {
		this.context.fillStyle = '#FFFFFF';
		this.context.fillRect(0, 0, this.width, this.height);
		this.generalBombs();

		console.log(this.bombs);
	},

	// 生成炸弹
	generalBombs : function() {
		for (var i = 0; i < this.bombsNum; i++) {
			var ele = {
				row : Math.floor(Math.random() * this.bombsNum),
				col : Math.floor(Math.random() * this.bombsNum)
			};

			!this.checkIsInBombs(ele) && this.bombs.push(ele);
		}
	},

	checkIsInBombs : function(ele) {
		for (var i = 0; i < this.bombs.length; i++) {
			if (ele.row === this.bombs[i].row && ele.col === this.bombs[i].col) {
				return true;
			}
		}
		return false;
	},

	onBoxImageLoaded : function() {
		for (var i = 0; i < this.row; i++) {
			for (var k = 0; k < this.col; k++) {
				this.context.drawImage(this.boxImage, k
								* this.boxImageConfig.width, i
								* this.boxImageConfig.height);
			}

		}
	},

	onCanvasClick : function(event, target, option) {
		var xy = event.xy, x = xy[0], y = xy[1], clickRow = Math.floor(y
				/ this.boxImageConfig.width), clickCol = Math.floor(x
				/ this.boxImageConfig.height);

		// 检测点击的box是否有炸弹

		if (this.checkIsInBombs({
					row : clickRow,
					col : clickCol
				})) {
			console.log('中奖了！');
		} else {
			// 统计当前点击的周围的炸弹个数
			var checkArray = [[0, 1], [0, -1], [1, 0], [-1, 0], [1, 1],
					[1, -1], [-1, 1], [-1, -1]], n = 0;

			for (var i = 0; i < checkArray.length; i++) {
				if (this.checkIsInBombs({
							row : clickRow + checkArray[i][0],
							col : clickCol + checkArray[i][1]
						})) {
					n++;
				}
			}

			console.log(n);

		}

	}
});

var minesWeeper = new Lone.Click.Canvas.MinesWeeper({
			row : 10,
			col : 10,
			bombsNum : 10,
			boxImageConfig : {
				height : 40,
				width : 40,
				src : 'images/box.png'
			}
		});